package hu.person.controller;

import lombok.extern.slf4j.Slf4j;
import hu.person.util.ResponseUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname AuthController
 * @Description TODO
 * @Date 2025/11/6 7:57
 * @Created by 24562
 */
@RestController
@RequestMapping("/log-in")
@Slf4j
public class AuthController {
    @GetMapping("/sign/in")
    public Object signIn(@RequestParam String account, @RequestParam String password) {
        boolean isPw = verifyPassword(account,password);
        if (!isPw) {
            return ResponseUtils.failed("password is failed");
        }

        String token = generateToken(account);

        // 生成cookie
        ResponseCookie cookie = ResponseCookie.from("token", token)
                .httpOnly(true)
                .secure(false)
                .path("/")
                .maxAge(30 * 60)
                .sameSite("Strict")
                .build();

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "登录成功");
        result.put("token", token);
        result.put("account", account);
        result.put("expiresIn", 30 * 60);

        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, cookie.toString())
                .body(result);
    }

    private String generateToken(String account) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("account", account);
        claims.put("loginTime", System.currentTimeMillis());
//        claims.put("userId", getUserIdByAccount(account)); // 从数据库获取用户ID

        // 实际编码逻辑（这里用Base64模拟）
        String payload = Base64.getEncoder().encodeToString(
                ("account:" + account + ",loginTime:" + System.currentTimeMillis()).getBytes()
        );

        return payload + "." + generateSignature(payload);
    }

    /**
     * 生成签名、提供更高的安全性
     */
    private String generateSignature(String payload) {
        try {
            String secretKey = "your-secret-key-here"; // 密钥，应该从配置读取

            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
            mac.init(secretKeySpec);

            byte[] signatureBytes = mac.doFinal(payload.getBytes());
            return Base64.getUrlEncoder().withoutPadding().encodeToString(signatureBytes);

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }

    /**
     * 验证签名
     */
    private boolean verifySignature(String payload, String receivedSignature) {
        String expectedSignature = generateSignature(payload);
        return expectedSignature.equals(receivedSignature);
    }

    private boolean verifyPassword(String account, String password) {
        return true;
    }
}
